import { MerchantAPI, UploadAPI } from '../../utils/api'

interface CategoryNode {
  categoryId: number;
  name: string;
  children?: CategoryNode[];
}

interface SpecOption {
  name: string;
  price: string;
  stock: string;
  marketPrice?: string;
  specDisplay?: string; // 可读的显示名称
  skuId?: number | string;
}

interface SpecGroup {
  groupName: string;
  options: string[];
}

interface FlavorGroup {
  groupName: string;
  options: string[];
  selected?: boolean; // 标记该分组是否被选中（选中后该分组的所有选项都可用）
}

interface ProductFormData {
  productId?: number | null;
  images: Array<{ url: string; localPath?: string }>;
  categoryPath: CategoryNode[];
  productTitle: string;
  price: string;
  stock: string;
  productCode: string;
  description: string;
  productType: 'normal' | 'package' | 'limited';
  services: Record<string, boolean>;
  flavors: string[]; // 口味选择（多选）- 兼容旧数据结构
  hasFlavor: boolean; // 是否有口味选择
  flavorGroups: FlavorGroup[]; // 口味分组（和规格分组一样的结构）
  packageFee: string;
  minOrderQuantity: string;
  boxCount: string;
  hasSpec: boolean; // 是否有规格
  specType: 'none' | 'portion' | 'cup' | 'custom'; // 规格类型：无规格、分量、杯型、自定义
  specGroups: SpecGroup[]; // 规格分组
  specOptions: SpecOption[]; // 规格选项（SKU）
  marketPrice?: string; // 无规格时的市场价
}

Page({
  data: {
    hasLogin: false,
    loading: false,
    uploading: false,
    statusBarHeight: 44,
    contentPaddingTop: 120,
    maxImages: 9,
    titleMaxLength: 60,
    descriptionMaxLength: 500,
    showCategoryModal: false,
    shouldReopenCategoryModal: false, // 标记是否需要重新打开分类选择弹窗
    categorySearchKeyword: '',
    categoryTree: [] as CategoryNode[],
    displayCategoryTree: [] as CategoryNode[],
    primaryList: [] as CategoryNode[],
    secondaryList: [] as CategoryNode[],
    tertiaryList: [] as CategoryNode[],
    categoryState: {
      primaryId: null,
      secondaryId: null,
      tertiaryId: null
    },
    categoryDisplay: '',
    moreInfoExpanded: false,
    pageTitle: '发布商品',
    currentProductId: null as number | null,
    formData: {
      productId: null,
      images: [],
      categoryPath: [],
      productTitle: '',
      price: '',
      stock: '',
      productCode: '',
      description: '',
      productType: 'normal',
      flavors: [],
      hasFlavor: false,
      flavorGroups: [
        { groupName: '辣度', options: ['不辣', '微辣', '中辣', '爆辣'], selected: false },
        { groupName: '甜度', options: ['无糖', '半糖', '七分糖', '全糖'], selected: false },
        { groupName: '冰度', options: ['不加冰', '少冰', '正常冰', '多冰'], selected: false }
      ] as FlavorGroup[],
      packageFee: '',
      minOrderQuantity: '1',
      boxCount: '1',
      hasSpec: false,
      specType: 'none',
      specGroups: [],
      specOptions: [],
      marketPrice: '' // 无规格时的市场价
    } as ProductFormData,
    specTypeOptions: [
      { key: 'none', label: '无规格', desc: '商品只有一个价格' },
      { key: 'portion', label: '分量', desc: '适合饭、面等商品（大份/中份/小份）' },
      { key: 'cup', label: '杯型', desc: '适合奶茶饮品等（大杯/中杯/小杯）' },
      { key: 'custom', label: '自定义', desc: '自定义规格名称和选项' }
    ],
    defaultSpecOptions: {
      portion: ['大份', '中份', '小份'],
      cup: ['大杯', '中杯', '小杯']
    },
    showFlavorModal: false, // 是否显示口味选择弹窗
    flavorOptionMap: {
      noSpicy: '不辣',
      mildSpicy: '微辣',
      mediumSpicy: '中辣',
      hotSpicy: '爆辣',
      noSugar: '无糖',
      halfSugar: '半糖',
      sevenSugar: '七分糖',
      fullSugar: '全糖',
      noIce: '不加冰',
      lessIce: '少冰',
      normalIce: '正常冰',
      moreIce: '多冰'
    },
    allFlavorOptions: [
      // 辣度
      { key: 'noSpicy', label: '不辣', group: 'spicy' },
      { key: 'mildSpicy', label: '微辣', group: 'spicy' },
      { key: 'mediumSpicy', label: '中辣', group: 'spicy' },
      { key: 'hotSpicy', label: '爆辣', group: 'spicy' },
      // 甜度
      { key: 'noSugar', label: '无糖', group: 'sugar' },
      { key: 'halfSugar', label: '半糖', group: 'sugar' },
      { key: 'sevenSugar', label: '七分糖', group: 'sugar' },
      { key: 'fullSugar', label: '全糖', group: 'sugar' },
      // 冰度
      { key: 'noIce', label: '不加冰', group: 'ice' },
      { key: 'lessIce', label: '少冰', group: 'ice' },
      { key: 'normalIce', label: '正常冰', group: 'ice' },
      { key: 'moreIce', label: '多冰', group: 'ice' }
    ] as Array<{ key: string; label: string; group: string }>,
    submissionMode: 'create',
    marketPrice: '' // 无规格时的市场价
  },

  async onLoad(options: Record<string, string>) {
    const mode = options?.mode || 'create';
    const productId = options?.productId ? Number(options.productId) : null;
    await this.initPage(mode, productId);
  },

  async onShow() {
    // 如果标记需要重新打开分类选择弹窗，先刷新分类数据
    if (this.data.shouldReopenCategoryModal) {
      this.setData({ shouldReopenCategoryModal: false });
      // 先刷新分类数据，然后再打开弹窗
      await this.fetchCategoryTree();
      // 延迟一下，确保分类数据已加载完成
      setTimeout(() => {
        this.openCategoryPicker();
      }, 200);
    } else {
      // 正常情况也刷新一下分类数据，确保数据是最新的
      this.fetchCategoryTree();
    }
  },

  async initPage(mode: string, productId: number | null) {
    this.checkLoginStatus();
    const statusBarHeight = this.getStatusBarHeight();
    const contentPaddingTop = statusBarHeight + 88;
    this.setData({
      statusBarHeight,
      contentPaddingTop,
      submissionMode: mode || 'create',
      currentProductId: productId,
      pageTitle: mode === 'edit' ? '编辑商品' : '发布商品'
    });
    await this.fetchCategoryTree();
    if (mode === 'edit' && productId) {
      await this.loadProductDetail(productId);
    }
  },

  getStatusBarHeight(): number {
    try {
      const systemInfo = wx.getSystemInfoSync();
      const statusBar = systemInfo.statusBarHeight || systemInfo.safeArea?.top || 20;
      return statusBar;
    } catch (e) {
      return 44;
    }
  },

  resolveCategoryPath(categoryId: number | null): CategoryNode[] {
    if (!categoryId) return [];
    const tree = this.data.categoryTree || [];
    const path: CategoryNode[] = [];

    const dfs = (nodes: CategoryNode[], trail: CategoryNode[]): boolean => {
      for (const node of nodes) {
        const track = [...trail, node];
        if (node.categoryId === categoryId) {
          path.push(...track);
          return true;
        }
        if (node.children && node.children.length) {
          if (dfs(node.children, track)) {
            return true;
          }
        }
      }
      return false;
    };

    dfs(tree, []);
    return path;
  },

  syncFlavorSelections(dishTags: string): FlavorGroup[] {
    const defaultGroups = [
      { groupName: '辣度', options: ['不辣', '微辣', '中辣', '爆辣'], selected: false },
      { groupName: '甜度', options: ['无糖', '半糖', '七分糖', '全糖'], selected: false },
      { groupName: '冰度', options: ['不加冰', '少冰', '正常冰', '多冰'], selected: false }
    ];

    if (!dishTags) {
      return defaultGroups;
    }

    try {
      // 尝试解析JSON格式（新格式）
      const parsed = JSON.parse(dishTags);
      if (Array.isArray(parsed)) {
        // 新格式：[{ groupName: "辣度", options: ["微辣", "中辣"] }]
        const savedGroups = parsed.map((item: any) => ({
          groupName: item.groupName || '',
          options: Array.isArray(item.options) ? item.options : [],
          selected: true // 已保存的分组标记为已选中
        }));
        
        // 合并默认分组（未保存的分组保持未选中状态）
        const result = [...savedGroups];
        defaultGroups.forEach(defaultGroup => {
          if (!result.find(g => g.groupName === defaultGroup.groupName)) {
            result.push(defaultGroup);
          }
        });
        
        return result;
      }
    } catch (e) {
      // 解析失败，可能是旧格式（逗号分隔）
      console.warn('口味数据解析失败，使用默认分组', e);
    }

    return defaultGroups;
  },

  detectSpecType(specGroups: SpecGroup[]): 'none' | 'portion' | 'cup' | 'custom' {
    if (!specGroups || !specGroups.length) {
      return 'none';
    }
    const firstName = specGroups[0].groupName || '';
    if (firstName.includes('分量')) {
      return 'portion';
    }
    if (firstName.includes('杯')) {
      return 'cup';
    }
    return 'custom';
  },

  parseSpecGroups(rawGroups: any[]): SpecGroup[] {
    if (!Array.isArray(rawGroups)) return [];
    return rawGroups.map(group => {
      let options: string[] = [];
      if (Array.isArray(group.specOptions)) {
        options = group.specOptions;
      } else if (group.externField1) {
        try {
          const parsed = JSON.parse(group.externField1);
          if (Array.isArray(parsed)) {
            options = parsed;
          }
        } catch (error) {
          console.warn('规格选项解析失败', error);
        }
      }
      const cleanedOptions = (options || [])
        .map((option: string) => (option || '').trim())
        .filter(Boolean);
      return {
        groupName: group.groupName || '规格',
        options: cleanedOptions
      };
    }).filter(group => group.options.length > 0);
  },

  formatSpecDisplay(specItems: any): string {
    if (!specItems || specItems === '{}' || specItems === '默认') {
      return '默认规格';
    }
    try {
      const parsed = typeof specItems === 'string' ? JSON.parse(specItems) : specItems;
      const values = Object.values(parsed || {}).filter(Boolean);
      return values.length ? values.join('/') : '默认规格';
    } catch (error) {
      return typeof specItems === 'string' ? specItems : '默认规格';
    }
  },

  parseSkuList(rawSkuList: any[]): SpecOption[] {
    if (!Array.isArray(rawSkuList)) return [];
    return rawSkuList.map((sku: any) => {
      let specItemsString = '';
      if (typeof sku.specItems === 'string') {
        specItemsString = sku.specItems;
      } else if (sku.specItems && typeof sku.specItems === 'object') {
        specItemsString = JSON.stringify(sku.specItems);
      } else {
        specItemsString = '{}';
      }
      return {
        name: specItemsString,
        specDisplay: this.formatSpecDisplay(sku.specItems || specItemsString),
        price: sku.price != null ? String(sku.price) : '',
        stock: sku.stock != null ? String(sku.stock) : '',
        marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : '',
        skuId: sku.skuId
      };
    });
  },

  async loadProductDetail(productId: number) {
    try {
      wx.showLoading({ title: '加载商品...', mask: true });
      const res = await MerchantAPI.getProductDetail(productId);
      const detail = res?.data || {};
      const images = detail.imageUrl ? [{ url: detail.imageUrl }] : [];
      const parsedGroups = this.parseSpecGroups(detail.specGroups || []);
      const parsedSkus = this.parseSkuList(detail.skuList || []);
      const hasStructuredSku = parsedSkus.some(option => option.specDisplay && option.specDisplay !== '默认规格');
      const hasSpec = parsedGroups.length > 0 && hasStructuredSku;

      let basePrice = detail.regionPrice != null ? String(detail.regionPrice) : '';
      let baseMarketPrice = detail.marketPrice != null ? String(detail.marketPrice) : '';
      let baseStock = detail.stockQuantity != null ? String(detail.stockQuantity) : '';

      if (!hasSpec && parsedSkus.length === 1) {
        basePrice = parsedSkus[0].price;
        baseMarketPrice = parsedSkus[0].marketPrice || baseMarketPrice;
        baseStock = parsedSkus[0].stock;
      }

      const categoryPath = this.resolveCategoryPath(detail.categoryId);
      const fallbackCategoryPath = categoryPath.length
        ? categoryPath
        : detail.categoryId
          ? [{ categoryId: detail.categoryId, name: detail.categoryName || '未分类' }]
          : [];
      const categoryDisplay = fallbackCategoryPath.map(item => item.name).join(' / ');

      const dishTags = detail.externField1 || detail.dishTags || '';
      const flavorGroups = this.syncFlavorSelections(dishTags);
      const hasFlavor = flavorGroups.some(group => group.selected);

      const updatedFormData: ProductFormData = {
        ...this.data.formData,
        productId,
        images,
        categoryPath: fallbackCategoryPath,
        productTitle: detail.name || '',
        description: detail.description || '',
        price: hasSpec ? '' : basePrice,
        stock: hasSpec ? '' : baseStock,
        marketPrice: hasSpec ? '' : baseMarketPrice,
        hasSpec,
        specType: hasSpec ? this.detectSpecType(parsedGroups) : 'none',
        specGroups: hasSpec ? parsedGroups : [],
        specOptions: hasSpec ? parsedSkus : [],
        hasFlavor: hasFlavor,
        flavorGroups
      };

      this.setData({
        formData: updatedFormData,
        categoryDisplay,
        currentProductId: productId
      });
    } catch (error) {
      console.error('加载商品详情失败', error);
      wx.showToast({
        title: '加载商品失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    if (token && userInfo) {
      this.setData({ hasLogin: true });
    } else {
      this.setData({ hasLogin: false });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  async fetchCategoryTree() {
    try {
      wx.showLoading({ title: '加载分类...', mask: true });
      const res = await MerchantAPI.getCategoryOptions();
      const categoryTree = (res?.data || []) as CategoryNode[];
      this.setData({
        categoryTree,
        displayCategoryTree: categoryTree,
        primaryList: categoryTree
      });
    } catch (error) {
      console.error('加载分类失败', error);
      wx.showToast({
        title: '加载分类失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  openCategoryPicker() {
    // 即使没有分类数据，也打开弹窗，这样用户才能点击"管理分类"按钮
    const primaryList = this.data.displayCategoryTree.length
      ? this.data.displayCategoryTree
      : this.data.categoryTree;
    
    // 如果没有分类数据，直接打开弹窗显示空状态，让用户可以去管理分类
    if (!primaryList.length) {
      this.setData({
        showCategoryModal: true,
        categorySearchKeyword: '',
        primaryList: [],
        secondaryList: [],
        tertiaryList: [],
        'categoryState.primaryId': null,
        'categoryState.secondaryId': null,
        'categoryState.tertiaryId': null
      });
      return;
    }
    
    const currentPath = this.data.formData.categoryPath;
    const defaultPrimaryId = currentPath[0]?.categoryId || primaryList[0]?.categoryId || null;
    const secondaryList = this.getSecondaryList(defaultPrimaryId, primaryList);
    const defaultSecondaryId = currentPath[1]?.categoryId || secondaryList[0]?.categoryId || null;
    const tertiaryList = this.getTertiaryList(defaultPrimaryId, defaultSecondaryId, primaryList);
    const defaultTertiaryId = currentPath[2]?.categoryId || tertiaryList[0]?.categoryId || null;

    this.setData({
      showCategoryModal: true,
      categorySearchKeyword: '',
      primaryList,
      secondaryList,
      tertiaryList,
      'categoryState.primaryId': defaultPrimaryId,
      'categoryState.secondaryId': defaultSecondaryId,
      'categoryState.tertiaryId': defaultTertiaryId
    });
  },

  closeCategoryModal() {
    this.setData({ showCategoryModal: false });
  },

  getSecondaryList(primaryId: number | null, tree: CategoryNode[]) {
    if (primaryId == null) return [];
    const primary = tree.find(item => item.categoryId === primaryId);
    if (!primary || !primary.children) return [];
    // 过滤掉没有名称的三级分类，避免弹窗中出现没有文字的灰色小块
    return primary.children.map(sec => ({
      ...sec,
      children: (sec.children || []).filter(child => child.name && child.name.trim())
    }));
  },

  getTertiaryList(primaryId: number | null, secondaryId: number | null, tree: CategoryNode[]) {
    if (primaryId == null || secondaryId == null) return [];
    const secondaryList = this.getSecondaryList(primaryId, tree);
    const secondary = secondaryList.find(item => item.categoryId === secondaryId);
    return secondary?.children || [];
  },

  selectPrimaryCategory(e: any) {
    const primaryId = Number(e.currentTarget.dataset.id);
    const secondaryList = this.getSecondaryList(primaryId, this.data.displayCategoryTree);
    const secondaryId = secondaryList[0]?.categoryId || null;
    const tertiaryList = this.getTertiaryList(primaryId, secondaryId, this.data.displayCategoryTree);
    const tertiaryId = tertiaryList[0]?.categoryId || null;
    this.setData({
      secondaryList,
      tertiaryList,
      'categoryState.primaryId': primaryId,
      'categoryState.secondaryId': secondaryId,
      'categoryState.tertiaryId': tertiaryId
    });
  },

  selectSecondaryCategory(e: any) {
    const secondaryId = Number(e.currentTarget.dataset.id);
    const tertiaryList = this.getTertiaryList(this.data.categoryState.primaryId, secondaryId, this.data.displayCategoryTree);
    const tertiaryId = tertiaryList[0]?.categoryId || null;
    this.setData({
      tertiaryList,
      'categoryState.secondaryId': secondaryId,
      'categoryState.tertiaryId': tertiaryId
    });
  },

  selectTertiaryCategory(e: any) {
    const tertiaryId = Number(e.currentTarget.dataset.id);
    this.setData({
      'categoryState.tertiaryId': tertiaryId
    });
  },

  onCategorySearchInput(e: any) {
    const keyword = (e.detail.value || '').trim();
    this.setData({ categorySearchKeyword: keyword });
    this.applyCategorySearch(keyword);
  },

  applyCategorySearch(keyword: string) {
    if (!keyword) {
      this.setData({
        displayCategoryTree: this.data.categoryTree,
        primaryList: this.data.categoryTree
      });
      return;
    }

    const filtered = this.data.categoryTree.map(primary => {
      const matchPrimary = primary.name.includes(keyword);
      const filteredSecondary = (primary.children || []).map(secondary => {
        const matchSecondary = secondary.name.includes(keyword);
        const filteredTertiary = (secondary.children || []).filter(ter => ter.name.includes(keyword));
        if (matchSecondary) {
          return secondary;
        }
        if (filteredTertiary.length) {
          return {
            ...secondary,
            children: filteredTertiary
          };
        }
        return null;
      }).filter(Boolean) as CategoryNode[];

      if (matchPrimary) {
        return primary;
      }
      if (filteredSecondary.length) {
        return {
          ...primary,
          children: filteredSecondary
        };
      }
      return null;
    }).filter(Boolean) as CategoryNode[];

    this.setData({
      displayCategoryTree: filtered.length ? filtered : [],
      primaryList: filtered.length ? filtered : []
    });
  },

  clearCategorySearch() {
    this.setData({
      categorySearchKeyword: '',
      displayCategoryTree: this.data.categoryTree,
      primaryList: this.data.categoryTree
    });
  },

  confirmCategorySelection() {
    const { primaryId, secondaryId, tertiaryId } = this.data.categoryState;
    const primaryList = this.data.displayCategoryTree.length ? this.data.displayCategoryTree : this.data.categoryTree;
    const primary = primaryList.find(item => item.categoryId === primaryId);
    const secondary = (primary?.children || []).find(item => item.categoryId === secondaryId);
    const tertiary = (secondary?.children || []).find(item => item.categoryId === tertiaryId);
    const categoryPath = [primary, secondary, tertiary].filter(Boolean) as CategoryNode[];

    if (!categoryPath.length) {
      wx.showToast({
        title: '请选择分类',
        icon: 'none'
      });
      return;
    }

    this.setData({
      showCategoryModal: false,
      categoryDisplay: categoryPath.map(item => item.name).join(' / '),
      'formData.categoryPath': categoryPath
    });
  },

  chooseImages() {
    const remaining = this.data.maxImages - this.data.formData.images.length;
    if (remaining <= 0) {
      wx.showToast({
        title: `最多上传${this.data.maxImages}张`,
        icon: 'none'
      });
      return;
    }
    wx.chooseImage({
      count: remaining,
      sizeType: ['compressed'],
      success: (res) => {
        const paths = res.tempFilePaths || [];
        if (paths.length) {
          this.uploadSelectedImages(paths);
        }
      }
    });
  },

  async uploadSelectedImages(paths: string[]) {
    if (!paths.length) return;
    this.setData({ uploading: true });
    wx.showLoading({ title: '上传中...' });
    try {
      const uploaded = await Promise.all(paths.map(async (path) => {
        try {
          const uploadRes = await UploadAPI.uploadFile(path);
          console.log('上传响应数据:', uploadRes);
          // 后端返回格式: { code: 200, msg: "操作成功", data: "https://xxx.com/xxx.png" }
          // 优先使用 data 字段（可能是字符串URL），其次是 data.url 等字段
          let url = '';
          if (uploadRes?.data) {
            if (typeof uploadRes.data === 'string') {
              // data 直接是 URL 字符串
              url = uploadRes.data;
            } else if (uploadRes.data.url) {
              // data 是对象，包含 url 字段
              url = uploadRes.data.url;
            } else if (uploadRes.data.fileUrl) {
              url = uploadRes.data.fileUrl;
            } else if (uploadRes.data.fileName) {
              url = uploadRes.data.fileName;
            }
          }
          if (!url) {
            url = uploadRes?.url || path;
          }
          console.log('最终使用的URL:', url);
          return {
            url,
            localPath: path
          };
        } catch (error) {
          console.error('上传失败', error);
          wx.showToast({
            title: '部分图片上传失败',
            icon: 'none'
          });
          return null;
        }
      }));
      const validImages = uploaded.filter(Boolean) as Array<{ url: string; localPath?: string }>;
      if (validImages.length) {
        const finalImages = [...this.data.formData.images, ...validImages].slice(0, this.data.maxImages);
        this.setData({
          'formData.images': finalImages
        });
      }
    } finally {
      wx.hideLoading();
      this.setData({ uploading: false });
    }
  },

  removeImage(e: any) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.formData.images];
    images.splice(index, 1);
    this.setData({
      'formData.images': images
    });
  },

  handleInput(e: any) {
    const field = e.currentTarget.dataset.field;
    if (!field) return;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  handleTextareaInput(e: any) {
    const value = e.detail.value;
    this.setData({
      'formData.description': value
    });
  },

  handleProductTypeChange(e: any) {
    const value = e.detail.value;
    this.setData({
      'formData.productType': value
    });
  },

  toggleMoreInfo() {
    this.setData({
      moreInfoExpanded: !this.data.moreInfoExpanded
    });
  },


  // 切换口味选择开关
  toggleHasFlavor(e: any) {
    const hasFlavor = e.detail.value;
    const flavorGroups = this.data.formData.flavorGroups.map(group => ({
      ...group,
      selectedOption: hasFlavor ? group.selectedOption : undefined
    }));
    this.setData({
      'formData.hasFlavor': hasFlavor,
      'formData.flavors': hasFlavor ? this.data.formData.flavors : [], // 兼容旧数据
      'formData.flavorGroups': flavorGroups
    });
  },

  // 切换整个口味分组的选中状态（点击分组名称）
  toggleFlavorGroup(e: any) {
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const flavorGroups = [...this.data.formData.flavorGroups];
    
    // 切换该分组的选中状态
    flavorGroups[groupIndex] = {
      ...flavorGroups[groupIndex],
      selected: !flavorGroups[groupIndex].selected
    };
    
    this.setData({
      'formData.flavorGroups': flavorGroups
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空方法，仅用于阻止事件冒泡
  },  // 更新口味分组选项
  updateFlavorGroupOption(e: any) {
    const { groupIndex, optionIndex } = e.currentTarget.dataset;
    const value = e.detail.value;
    const flavorGroups = [...this.data.formData.flavorGroups];
    if (flavorGroups[groupIndex] && flavorGroups[groupIndex].options) {
      const oldOption = flavorGroups[groupIndex].options[optionIndex];
      flavorGroups[groupIndex].options[optionIndex] = value;
      // 如果更新的选项是当前选中的，同步更新选中值
      if (flavorGroups[groupIndex].selectedOption === oldOption) {
        flavorGroups[groupIndex].selectedOption = value || undefined;
      }
      this.setData({
        'formData.flavorGroups': flavorGroups
      });
      // 更新flavors数组
      const flavors: string[] = [];
      flavorGroups.forEach(g => {
        if (g.selectedOption) {
          flavors.push(g.selectedOption);
        }
      });
      this.setData({
        'formData.flavors': flavors
      });
    }
  },

  // 添加口味分组选项
  addFlavorGroupOption(e: any) {
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const flavorGroups = [...this.data.formData.flavorGroups];
    if (flavorGroups[groupIndex]) {
      flavorGroups[groupIndex].options.push('');
      this.setData({
        'formData.flavorGroups': flavorGroups
      });
    }
  },

  // 删除口味分组选项
  removeFlavorGroupOption(e: any) {
    const { groupIndex, optionIndex } = e.currentTarget.dataset;
    const flavorGroups = [...this.data.formData.flavorGroups];
    if (flavorGroups[groupIndex] && flavorGroups[groupIndex].options.length > 1) {
      const removedOption = flavorGroups[groupIndex].options[optionIndex];
      flavorGroups[groupIndex].options.splice(optionIndex, 1);
      // 如果删除的是当前选中的选项，清除选中状态
      if (flavorGroups[groupIndex].selectedOption === removedOption) {
        flavorGroups[groupIndex].selectedOption = undefined;
      }
      this.setData({
        'formData.flavorGroups': flavorGroups
      });
      // 更新flavors数组
      const flavors: string[] = [];
      flavorGroups.forEach(g => {
        if (g.selectedOption) {
          flavors.push(g.selectedOption);
        }
      });
      this.setData({
        'formData.flavors': flavors
      });
    }
  },

  // 更新口味分组名称
  updateFlavorGroupName(e: any) {
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const value = e.detail.value;
    const flavorGroups = [...this.data.formData.flavorGroups];
    if (flavorGroups[groupIndex]) {
      flavorGroups[groupIndex].groupName = value;
      this.setData({
        'formData.flavorGroups': flavorGroups
      });
    }
  },

  // 添加口味分组
  addFlavorGroup() {
    const flavorGroups = [...this.data.formData.flavorGroups];
    flavorGroups.push({
      groupName: '新口味',
      options: ['']
    });
    this.setData({
      'formData.flavorGroups': flavorGroups
    });
  },

  // 删除口味分组
  removeFlavorGroup(e: any) {
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const flavorGroups = [...this.data.formData.flavorGroups];
    if (flavorGroups.length > 1) {
      flavorGroups.splice(groupIndex, 1);
      this.setData({
        'formData.flavorGroups': flavorGroups
      });
      // 更新flavors数组
      const flavors: string[] = [];
      flavorGroups.forEach(g => {
        if (g.selectedOption) {
          flavors.push(g.selectedOption);
        }
      });
      this.setData({
        'formData.flavors': flavors
      });
    } else {
      wx.showToast({
        title: '至少保留一个口味分组',
        icon: 'none'
      });
    }
  },

  noop() {},

  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 规格相关方法
  toggleHasSpec(e: any) {
    const hasSpec = e.detail.value;
    this.setData({
      'formData.hasSpec': hasSpec,
      'formData.specType': hasSpec ? 'portion' : 'none'
    });
    if (hasSpec) {
      this.initSpecGroups();
    } else {
      this.setData({
        'formData.specGroups': [],
        'formData.specOptions': []
      });
    }
  },

  selectSpecType(e: any) {
    const specType = e.currentTarget.dataset.type;
    this.setData({
      'formData.specType': specType
    });
    if (specType !== 'none') {
      this.initSpecGroups();
    }
  },

  initSpecGroups() {
    const { formData } = this.data;
    const specType = formData.specType;
    if (specType === 'none') {
      this.setData({
        'formData.specGroups': [],
        'formData.specOptions': []
      });
      return;
    }

    let defaultOptions: string[] = [];
    let groupName = '规格';
    if (specType === 'portion') {
      defaultOptions = this.data.defaultSpecOptions.portion;
      groupName = '分量';
    } else if (specType === 'cup') {
      defaultOptions = this.data.defaultSpecOptions.cup;
      groupName = '杯型';
    } else if (specType === 'custom') {
      // 自定义规格，默认创建一个空分组
      const specGroups: SpecGroup[] = [{
        groupName: '规格',
        options: ['']
      }];
      this.setData({
        'formData.specGroups': specGroups,
        'formData.specOptions': []
      });
      // 自定义时不需要自动生成SKU，等用户编辑后再生成
      return;
    }

    // 创建规格分组（保留现有的规格分组，如果存在）
    const existingGroups = formData.specGroups || [];
    let specGroups: SpecGroup[];
    
    // 如果已有规格分组且第一个分组名称匹配，则保留并更新选项
    if (existingGroups.length > 0 && existingGroups[0].groupName === groupName) {
      specGroups = [...existingGroups];
      specGroups[0].options = [...defaultOptions];
    } else {
      // 否则创建新的规格分组
      specGroups = [{
        groupName,
        options: [...defaultOptions]
      }];
    }

    // 生成SKU列表（笛卡尔积，支持多个规格分组）
    this.generateSkuListFromSpecGroups(specGroups);
  },

  // 更新规格分组中的选项
  updateSpecGroupOption(e: any) {
    const { groupIndex, optionIndex } = e.currentTarget.dataset;
    const value = e.detail.value;
    const specGroups = [...this.data.formData.specGroups];
    if (specGroups[groupIndex] && specGroups[groupIndex].options) {
      specGroups[groupIndex].options[optionIndex] = value;
      this.setData({
        'formData.specGroups': specGroups
      });
      // 重新生成SKU列表
      this.generateSkuListFromSpecGroups(specGroups);
    }
  },

  // 添加规格分组选项
  addSpecGroupOption(e: any) {
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const specGroups = [...this.data.formData.specGroups];
    if (specGroups[groupIndex]) {
      specGroups[groupIndex].options.push('');
      this.setData({
        'formData.specGroups': specGroups
      });
      // 重新生成SKU列表
      this.generateSkuListFromSpecGroups(specGroups);
    }
  },

  // 删除规格分组选项
  removeSpecGroupOption(e: any) {
    const { groupIndex, optionIndex } = e.currentTarget.dataset;
    const specGroups = [...this.data.formData.specGroups];
    if (specGroups[groupIndex] && specGroups[groupIndex].options.length > 1) {
      specGroups[groupIndex].options.splice(optionIndex, 1);
      this.setData({
        'formData.specGroups': specGroups
      });
      // 重新生成SKU列表
      this.generateSkuListFromSpecGroups(specGroups);
    }
  },

  // 根据规格分组生成SKU列表（笛卡尔积）
  generateSkuListFromSpecGroups(specGroups: SpecGroup[]) {
    const { formData } = this.data;
    
    // 过滤掉空选项
    const validGroups = specGroups.filter(g => g.options && g.options.length > 0 && g.options.some(o => o && o.trim()));
    if (validGroups.length === 0) {
      this.setData({
        'formData.specOptions': []
      });
      return;
    }

    // 生成所有规格组合（笛卡尔积）
    const combinations: Array<{ [key: string]: string }> = [];
    const generateCombinations = (groups: SpecGroup[], index: number, current: { [key: string]: string }) => {
      if (index === groups.length) {
        combinations.push({ ...current });
        return;
      }
      const group = groups[index];
      group.options.filter(o => o && o.trim()).forEach(option => {
        generateCombinations(groups, index + 1, { ...current, [group.groupName]: option });
      });
    };

    generateCombinations(validGroups, 0, {});

    // 为每个组合创建SKU选项
    const existingOptions = this.data.formData.specOptions || [];
    const specOptions: (SpecOption & { specDisplay?: string })[] = combinations.map((combo, index) => {
      const specItemsStr = JSON.stringify(combo);
      // 生成可读的显示名称：如"大份"或"微辣/单人份"
      const specDisplay = this.formatSpecDisplay(combo);
      
      // 查找是否已存在相同的SKU，保留其价格和库存
      const existing = existingOptions.find(opt => {
        try {
          if (!opt.name) return false;
          const existingSpec = JSON.parse(opt.name);
          return JSON.stringify(existingSpec) === specItemsStr;
        } catch {
          // 兼容旧格式（直接的选项字符串）
          return opt.name === specItemsStr || opt.specDisplay === specDisplay;
        }
      });
      
      return {
        name: specItemsStr,
        specDisplay: specDisplay, // 可读的显示名称
        price: existing?.price || formData.price || '',
        stock: existing?.stock || formData.stock || '',
        marketPrice: existing?.marketPrice || existing?.price || formData.price || ''
      };
    });

    // 同时更新规格分组（确保规格分组数据同步）
    this.setData({
      'formData.specGroups': specGroups,
      'formData.specOptions': specOptions
    });
  },

  updateSpecOptionPrice(e: any) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    const specOptions = [...this.data.formData.specOptions];
    specOptions[index].price = value;
    if (!specOptions[index].marketPrice) {
      specOptions[index].marketPrice = value;
    }
    this.setData({
      'formData.specOptions': specOptions
    });
  },

  updateSpecOptionMarketPrice(e: any) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    const specOptions = [...this.data.formData.specOptions];
    specOptions[index].marketPrice = value;
    this.setData({
      'formData.specOptions': specOptions
    });
  },

  updateSpecOptionStock(e: any) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    const specOptions = [...this.data.formData.specOptions];
    specOptions[index].stock = value;
    this.setData({
      'formData.specOptions': specOptions
    });
  },

  updateSpecGroupName(e: any) {
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const value = e.detail.value;
    const specGroups = [...this.data.formData.specGroups];
    if (specGroups[groupIndex]) {
      specGroups[groupIndex].groupName = value;
      this.setData({
        'formData.specGroups': specGroups
      });
      // 重新生成SKU列表
      this.generateSkuListFromSpecGroups(specGroups);
    }
  },

  addCustomSpecGroup() {
    const specGroups = [...this.data.formData.specGroups];
    specGroups.push({
      groupName: '新规格',
      options: ['']
    });
    this.setData({
      'formData.specGroups': specGroups
    });
    this.generateSkuListFromSpecGroups(specGroups);
  },

  removeSpecGroup(e: any) {
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const specGroups = [...this.data.formData.specGroups];
    specGroups.splice(groupIndex, 1);
    this.setData({
      'formData.specGroups': specGroups
    });
    // 重新生成SKU列表
    this.generateSkuListFromSpecGroups(specGroups);
  },

  goCategoryManager() {
    // 设置标记，表示从分类选择弹窗跳转到分类管理页面
    this.setData({ 
      showCategoryModal: false,
      shouldReopenCategoryModal: true 
    }, () => {
      wx.navigateTo({
        url: '/pages/category-manage/category-manage'
      });
    });
  },

  submitProduct() {
    if (this.data.loading) return;
    if (!this.validateForm()) {
      return;
    }
    this.setData({ loading: true });
    const isEditMode = this.data.submissionMode === 'edit' && !!this.data.currentProductId;
    wx.showLoading({ title: isEditMode ? '提交修改...' : '提交中...', mask: true });

    const formData = this.data.formData;
    const categoryPath = formData.categoryPath;
    const leafCategory = categoryPath[categoryPath.length - 1];
    const primaryImage = formData.images[0]?.url || '';

    // 构建规格分组（规格影响价格）
    // 格式：{ groupName: string, sortOrder: number, specOptions: string[] }
    const specGroups: any[] = [];
    if (formData.hasSpec && formData.specGroups.length > 0) {
      formData.specGroups.forEach((group, index) => {
        // 过滤掉空选项
        const validOptions = (group.options || []).filter((opt: string) => opt && opt.trim());
        if (validOptions.length > 0) {
          specGroups.push({
            groupName: group.groupName,
            specOptions: validOptions,
            sortOrder: index + 1
          });
        }
      });
    }

    // 构建SKU列表
    // 格式：{ specItems: string (JSON字符串), price: number, marketPrice: number, stock: number, sortOrder: number }
    const skuList: any[] = [];
    if (formData.hasSpec && formData.specOptions.length > 0) {
      // 有规格：每个规格组合对应一个SKU
      formData.specOptions.forEach((option, index) => {
        if (option.name && option.price && option.stock !== undefined && option.stock !== '') {
          // specItems应该是JSON字符串格式，如：{"辣度":"微辣","分量":"单人份"}
          const specItemsStr = option.name; // 已经是JSON字符串格式
          
          skuList.push({
            specItems: specItemsStr,
            price: Number(option.price),
            marketPrice: option.marketPrice ? Number(option.marketPrice) : Number(option.price),
            stock: Number(option.stock),
            sortOrder: index + 1
          });
        }
      });
    } else {
      // 无规格：只有一个默认SKU
      const marketPrice = formData.marketPrice ? Number(formData.marketPrice) : Number(formData.price);
      skuList.push({
        specItems: '{}', // 无规格时使用空JSON对象
        price: Number(formData.price),
        marketPrice: marketPrice,
        stock: Number(formData.stock || 0),
        sortOrder: 1
      });
    }

    if (skuList.length === 0) {
      wx.hideLoading();
      this.setData({ loading: false });
      wx.showToast({
        title: '请至少设置一个规格或价格',
        icon: 'none'
      });
      return;
    }

    // 构建口味标签（口味不影响价格，只作为商品的可选项标签）
    // 新逻辑：只包含已选中分组的所有选项
    let dishTags = '';
    if (formData.hasFlavor && formData.flavorGroups.length > 0) {
      const selectedFlavorGroups = formData.flavorGroups.filter(group => group.selected);
      
      if (selectedFlavorGroups.length > 0) {
        // 将每个选中分组的信息构建成JSON格式
        const flavorData = selectedFlavorGroups.map(group => ({
          groupName: group.groupName,
          options: group.options
        }));
        
        // 转为JSON字符串存储
        dishTags = JSON.stringify(flavorData);
      }
    }

    if (!leafCategory || !leafCategory.categoryId) {
      wx.hideLoading();
      this.setData({ loading: false });
      wx.showToast({
        title: '请选择分类',
        icon: 'none'
      });
      return;
    }

    // 构建提交数据（匹配后端格式）
    const basePayload: any = {
      dishName: formData.productTitle.trim(),
      categoryId: leafCategory?.categoryId,
      description: formData.description || '',
      imageUrl: primaryImage,
      dishTags: dishTags || '', // 口味标签
      isRecommended: dishTags ? '1' : '0', // 有标签时推荐
    };

    if (isEditMode) {
      const updatePayload = {
        ...basePayload,
        dishId: this.data.currentProductId
      };
      MerchantAPI.updateProduct(updatePayload)
        .then(() => {
          wx.showToast({
            title: '提交成功，等待审核',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 700);
        })
        .catch((error) => {
          console.error('更新商品失败', error);
        })
        .finally(() => {
          wx.hideLoading();
          this.setData({ loading: false });
        });
      return;
    }

    const createPayload: any = {
      ...basePayload,
      skuList
    };

    if (specGroups.length > 0) {
      createPayload.specGroups = specGroups;
    }

    MerchantAPI.createProduct(createPayload)
      .then(() => {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 700);
      })
      .catch((error) => {
        console.error('创建商品失败', error);
      })
      .finally(() => {
        wx.hideLoading();
        this.setData({ loading: false });
      });
  },

  validateForm(): boolean {
    const formData = this.data.formData;
    if (!formData.images.length) {
      wx.showToast({ title: '请上传商品图片', icon: 'none' });
      return false;
    }
    if (!formData.categoryPath.length) {
      wx.showToast({ title: '请选择商品分类', icon: 'none' });
      return false;
    }
    if (!formData.productTitle.trim()) {
      wx.showToast({ title: '请输入商品标题', icon: 'none' });
      return false;
    }

    // 根据是否有规格进行验证
    if (formData.hasSpec) {
      // 有规格：验证规格分组和SKU
      if (!formData.specGroups || formData.specGroups.length === 0) {
        wx.showToast({ title: '请至少添加一个规格分组', icon: 'none' });
        return false;
      }
      
      // 验证规格分组是否有有效的选项
      for (let i = 0; i < formData.specGroups.length; i++) {
        const group = formData.specGroups[i];
        if (!group.groupName || !group.groupName.trim()) {
          wx.showToast({ title: `规格分组${i + 1}的名称不能为空`, icon: 'none' });
          return false;
        }
        if (!group.options || group.options.length === 0 || !group.options.some((opt: string) => opt && opt.trim())) {
          wx.showToast({ title: `规格分组"${group.groupName}"至少需要一个选项`, icon: 'none' });
          return false;
        }
      }
      
      // 验证SKU列表
      if (!formData.specOptions || formData.specOptions.length === 0) {
        wx.showToast({ title: '请至少添加一个SKU选项', icon: 'none' });
        return false;
      }
      
      for (let i = 0; i < formData.specOptions.length; i++) {
        const option = formData.specOptions[i];
        if (!option.name || !option.name.trim()) {
          wx.showToast({ title: `SKU选项${i + 1}的规格不能为空`, icon: 'none' });
          return false;
        }
        if (!option.price || Number(option.price) <= 0) {
          wx.showToast({ title: `SKU选项${i + 1}的价格不正确`, icon: 'none' });
          return false;
        }
        if (option.stock === undefined || option.stock === '' || Number(option.stock) < 0) {
          wx.showToast({ title: `SKU选项${i + 1}的库存不正确`, icon: 'none' });
          return false;
        }
      }
    } else {
      // 无规格：验证基础价格和库存
      if (!formData.price || Number(formData.price) <= 0) {
        wx.showToast({ title: '请输入正确的价格', icon: 'none' });
        return false;
      }
      if (!formData.stock || Number(formData.stock) < 0) {
        wx.showToast({ title: '请输入库存', icon: 'none' });
        return false;
      }
    }

    return true;
  }
});

